package com.orientation.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.orientation.commom.exception.CustomException;
import com.orientation.entity.Article;
import com.orientation.entity.ArticleCate;
import com.orientation.entity.User;
import com.orientation.mapper.ArticleCateMapper;
import com.orientation.mapper.ArticleMapper;
import com.orientation.service.ArticleService;
import com.orientation.utils.BeanConvertUtils;
import com.orientation.utils.PageUtils;
import com.orientation.vo.ArticleVo;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.Collator;
import java.util.*;
import java.util.stream.Collectors;

import static java.util.stream.Collectors.toList;

/**
 * <p>
 * 文章 服务实现类
 * </p>
 *
 * @author xuandian
 * @since 2022-3-9
 */
@Service
public class ArticleServiceImpl extends ServiceImpl<ArticleMapper, Article> implements ArticleService {
    @Resource
    private ArticleMapper articleMapper;

    @Resource
    private ArticleCateMapper articleCateMapper;
    @Resource
    private HttpServletRequest request;
    @Resource
    private ArticleService articleService;
    @Resource
    private FilesService filesService;


    private List<Article> queryArticle(String cid, String title, String newsTime, String releaseType) {
        List<Article> articles = new ArrayList<>();
        LambdaQueryWrapper<Article> query = new LambdaQueryWrapper<>();

        if (!StringUtils.isEmpty(cid)) {
            query.like(Article::getCid, cid);
        }

        if (!StringUtils.isEmpty(newsTime)) {
            query.like(Article::getNewsTime, newsTime);
        }
        if (!StringUtils.isEmpty(releaseType)) {
            query.eq(Article::getReleaseType, releaseType);
        }
        if (!StringUtils.isEmpty(title)) {
            query.like(Article::getTitle, title);
        }
        List<Article> articles1 = articleMapper.selectList(query);
        if (!CollectionUtils.isEmpty(articles1)) {
            comparatorForChina(articles1);
            //去重
            articles = articles1.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(c -> c.getTitle()))), ArrayList::new));
        }
        return articles;
    }

    @Override
    public Page<ArticleVo> queryByMyArticle(Integer pageNum, Integer pageSize) {
        //从缓存获取当前登录这用户信息
        User user = (User) request.getSession().getAttribute("user");
        if (user == null || StringUtils.isEmpty(user.getLoginName())) {
            throw new CustomException("18", "请重新登录");
        }
        List<Article> articles = articleMapper.selectList(new LambdaQueryWrapper<Article>()
                // .eq(Article::getDeleted, 0)
                .eq(Article::getCreateUser, user.getLoginName()).eq(Article::getReleaseType, 1)
        );
        List<ArticleVo> articleVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(articles)) {
            //去重后的记录
            ArrayList<Article> collect = articles.stream().collect(Collectors.collectingAndThen(Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(Article::getTitle))), ArrayList::new));
            //中文排序
            comparatorForChina(collect);
            List<String> collectCollegeId = articles.stream().map(Article::getCid).distinct().collect(Collectors.toList());
            List<ArticleCate> colleges = articleCateMapper.selectList(new LambdaQueryWrapper<ArticleCate>().in(ArticleCate::getSid, collectCollegeId));
            articleVos = BeanConvertUtils.copyListProperties(collect, ArticleVo::new);
            for (ArticleVo articleVo : articleVos) {
                for (ArticleCate articleCate : colleges) {
                    if (articleCate.getSid().equals(articleVo.getCid())) {
                        articleVo.setName(articleCate.getName());
                    }
                }
            }
        }
        return PageUtils.getPage(articleVos, pageNum, pageSize);
    }

    @Override
    public IPage<ArticleVo> queryArticleVo(Integer pageNum, Integer pageSize, String cid, String title, String newsTime, String releaseType) {
        List<Article> articles = queryArticle(cid, title, newsTime, releaseType);
        List<ArticleVo> articleVos = new ArrayList<>();
        if (!CollectionUtils.isEmpty(articles)) {
            articleVos = BeanConvertUtils.copyListProperties(articles, ArticleVo::new);
            List<String> collectCollegeId = articles.stream().map(Article::getCid).distinct().collect(Collectors.toList());
            List<ArticleCate> colleges = articleCateMapper.selectList(new LambdaQueryWrapper<ArticleCate>().in(ArticleCate::getSid, collectCollegeId));
            for (ArticleVo articleVo : articleVos) {
                for (ArticleCate articleCate : colleges) {
                    if (articleCate.getSid().equals(articleVo.getCid())) {
                        articleVo.setName(articleCate.getName());
                    }
                }
            }
        }
        if (CollectionUtils.isEmpty(articleVos)) {
            return new Page<>();
        }

        return PageUtils.getPage(articleVos, pageNum, pageSize);
    }

    @Override
    public void updateStates(Article article) {

        if (article != null && !StringUtils.isEmpty(article.getSid()) && article.getReleaseType() != null) {
            updateById(article);
        } else {
            throw new CustomException("18", "sid未填写");
        }
    }

    @Override
    public void insertSchool(MultipartFile[] files, String title, String author) {
        if (!org.springframework.util.StringUtils.hasLength(title)) {
            throw new CustomException("18", "标题必填");
        }
        if (!org.springframework.util.StringUtils.hasLength(author)) {
            throw new CustomException("18", "作者必填");
        }
        Article one = articleService.getOne(Wrappers.<Article>lambdaQuery().eq(Article::getTitle, title));
        if (one != null) {
            throw new CustomException("18", "此内容已经存在，请不要重复添加");
        }
        Article article = new Article();
        article.setTitle(title);
        article.setCid("4");
        article.setAuthor(author);
        article.setReleaseType("1");
        //文件上传
        if (files != null && files.length > 0) {
            List<String> stringUrls = filesService.getStringUrls(files);
            if (!CollectionUtils.isEmpty(stringUrls)) {
                article.setContent(stringUrls == null ? null : org.apache.commons.lang3.StringUtils.join(stringUrls, ","));
            }
        }
        save(article);
    }

    @Override
    public void updateSchoolNew(MultipartFile[] files, String sid, List<String> urls, String title, String author) {
        Article article = new Article();

        String content = "";
        if (CollectionUtils.isEmpty(urls)) {
            article.setContent(null);
        } else {
            List<String> strings = urls.stream().distinct().collect(toList());
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : strings) {
                stringBuffer.append(s);
                stringBuffer.append(",");
            }
            content = stringBuffer.toString().substring(0, stringBuffer.length() - 1);
        }
        if (files != null && files.length > 0) {
            List<String> stringUrls = filesService.getStringUrls(files);
            if (!CollectionUtils.isEmpty(stringUrls)) {
                article.setContent(stringUrls == null ? null : org.apache.commons.lang3.StringUtils.join(stringUrls, ","));
            }
        }
        if (org.springframework.util.StringUtils.hasLength(content) && org.springframework.util.StringUtils.hasLength(article.getContent())) {
            article.setContent(content + "," + article.getContent());
        }
        if (org.springframework.util.StringUtils.hasLength(content) && !org.springframework.util.StringUtils.hasLength(article.getContent())) {
            article.setContent(content);
        }
        article.setSid(sid);
        article.setTitle(title);
        article.setAuthor(author);
        updateById(article);
    }

    @Override
    public void insertArticle(Article article) {
        if (!ObjectUtils.isEmpty(article) && !StringUtils.isEmpty(article.getTitle()) && !StringUtils.isEmpty(article.getCid())) {
            Article one = this.getOne(Wrappers.<Article>lambdaQuery().eq(Article::getTitle, article.getTitle()).eq(Article ::getCid,article.getCid()));
            if (!ObjectUtils.isEmpty(one)) {
                throw  new CustomException("18","此标题名数据存在请勿重复添加");
            }else {
                this.save(article);
            }

        }else {
                throw  new CustomException("18","必要信息没有填写");
        }

    }


    /**
     * 按中文首字母排序
     *
     * @param result
     * @return result
     */
    private List<Article> comparatorForChina(List<Article> result) {
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        //先类型
        Collections.sort(result, (o1, o2) -> comparator.compare(o1.getCid(), o2.getCid()));
        //在标题
        Collections.sort(result, (o1, o2) -> comparator.compare(o1.getTitle(), o2.getTitle()));
        return result;
    }

//    /**
//     * 按中文首字母排序
//     *
//     * @param result
//     * @return result
//     */
//    private List<Article> comparatorForChinaTitle(List<Article> result) {
//        Comparator comparator = Collator.getInstance(Locale.CHINA);
//        Collections.sort(result, (o1, o2) -> comparator.compare(o1.getTitle(), o2.get()));
//        return result;
//    }

}
